package com.elvish.efast.system.aspect;

import com.elvish.efast.common.entity.Page;
import com.elvish.efast.common.entity.TableResponse;
import com.elvish.efast.common.enums.ResultCode;
import com.elvish.efast.model.AbstractModel;
import com.elvish.efast.system.anno.NeedPage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.nutz.lang.Strings;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 分页切面
 *
 * @author elvish
 * @date 2018/11/13 16:49
 * @blog oschina(https : / / my.oschina.net / xiaozhutefannao)
 */
@Component
@Aspect
@Slf4j
public class PageAspect {

    @Around("@annotation(needPage)")
    public Object doAround(ProceedingJoinPoint pjp, NeedPage needPage) {
        Object res = null;
        try {
            boolean isTable = needPage.isTable();
            if (isTable) {
                Page page = null;
                Object[] args = pjp.getArgs();
                for (int i = 0; i < args.length; i++) {
                    if (args[i] instanceof Page) {
                        page = (Page) args[i];
                        if (page != null) {
                            PageHelper.startPage(page.getPage(), page.getLimit());
                        }
                        break;
                    }
                }
                res = pjp.proceed();
                if (page != null) {
                    TableResponse response = (TableResponse) res;
                    PageInfo<AbstractModel> pageInfo = new PageInfo<>((List<AbstractModel>) response.getData(), page.getLimit());
                    response.setCode(ResultCode.SUCCESS.getCode());
                    response.setMsg(ResultCode.SUCCESS.getMsg());
                    response.setCount(pageInfo.getTotal());
                }
            } else {
                // TODO 暂不考虑除表格之外的分页
            }
        } catch (Throwable e) {
            log.error("分页切面异常", e);
        }
        return res;
    }


}
